package com.topscomm.mpm.appController;

import com.topscomm.app.AppController;
import com.topscomm.app.pojo.AppPageEntity;
import com.topscomm.app.service.IAppPageService;
import com.topscomm.basic.BasicService;
import com.topscomm.basic.util.SQLAdapter;
import com.topscomm.cbo.pojo.CboApprovalNodeEntity;
import com.topscomm.cbo.service.ICboApprovalFlowInsService;
import com.topscomm.cbo.service.ICboApprovalNodeInsService;
import com.topscomm.cbo.service.ICboApprovalNodeService;
import com.topscomm.cbo.service.ICboDeptService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;
import com.topscomm.tap.common.DatacodeCache;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("app/appapproval")
public class AppApprovalController extends AppController<AppPageEntity, IAppPageService> {
    @Resource(name = "cboApprovalNodeInsService")
    ICboApprovalNodeInsService cboApprovalNodeInsService;
    @Resource(name = "cboApprovalFlowInsService")
    ICboApprovalFlowInsService cboApprovalFlowInsService;
    @Resource(name = "cboDeptService")
    ICboDeptService cboDeptService;
    @Resource(name = "cboApprovalNodeService")
    ICboApprovalNodeService cboApprovalNodeService;

    /**
     * @return
     * @throws Exception
     * @throws
     * @Title: myOffApprovalList
     * @return: String
     * @Description: 手机端返回用户未审批以及审批历史列表以及待审批单据数目
     */
    @GetMapping(value = "/myApprovalList")
    public ResponseResult<Object> myApprovalList(@RequestParam(required = false) Map<String, Object> paraMap) throws Exception {
        Map result = new HashMap<>();
        List<Map<String, Object>> listDataMap = new ArrayList<Map<String, Object>>();
        String doctType = ConvertUtil.convertToString(paraMap.get("doctype"));
        List<Map<String, Object>> listOffDocTypes = datacodeCache.getCodeListMap(doctType, "", "sortcode");
        StringBufferProxy docType = new StringBufferProxy();
        for (int num = 0; num < listOffDocTypes.size(); num++) {
            if (num != listOffDocTypes.size() - 1) {
                docType.appendSingle("'{0}',", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            } else {
                docType.appendSingle("'{0}'", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            }
        }
        Map dataMap = new HashMap<>();
        int page = ConvertUtil.convertToInt(paraMap.get("currentPage"));
        int rows = ConvertUtil.convertToInt(paraMap.get("pageSize"));
        String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
        String sord = ConvertUtil.convertToString(paraMap.get("sord"));
        String state = ConvertUtil.convertToString(paraMap.get("state"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("select tmpTable.*,'ehr' as system from ( ");
        sql.appendSingle(" select  CboApprovalFlowIns.extendfield2 as deptcode,CboApprovalFlowIns.extendfield3 as usercode,CboApprovalFlowIns.submitdate as docdate,CboApprovalFlowIns.extendfield1 as docno,CboApprovalFlowIns.sourcetype as doctype, ");
        sql.appendSingle(
                " CboApprovalNode.name nodename,CboApprovalNode.approvalaction,approvalparam,CboApprovalNode.mobiledataaction,CboApprovalNode.mobileform,CboApprovalNode.extendfield9,CboApprovalNode.extendfield10,CboApprovalNode.ismobilapproval,  ");
        sql.appendSingle(" CboApprovalNodeIns.approvalopinion,");
        sql.appendSingle(
                " CboApprovalNodeIns.id,CboApprovalNodeIns.extendfield2,CboApprovalNodeIns.flowinsid,CboApprovalNodeIns.sourceid,CboApprovalNodeIns.sourcetype,");
        sql.appendSingle(" CboApprovalNodeIns.state,CboApprovalNodeIns.approvaldate ");
        sql.appendSingle(" from CboApprovalNodeIns  ");
        sql.appendSingle(" inner join CboApprovalFlowIns on CboApprovalNodeIns.flowinsid = CboApprovalFlowIns.id ");
        sql.appendSingle(" inner join CboApprovalFlow on CboApprovalFlowIns.flowid = CboApprovalFlow.id ");
        sql.appendSingle(" inner join CboApprovalNode on CboApprovalNodeIns.nodeid = CboApprovalNode.id ");
        sql.appendSingle(" left join CboDept on CboApprovalFlowIns.extendfield2 = CboDept.code ");
        sql.appendSingle(" left join CboUser on CboApprovalFlowIns.extendfield3 = CboUser.code ");
        if (paraMap.containsKey("qry_doctype")) {
            String value = paraMap.get("qry_doctype").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" where CboApprovalNodeIns.sourcetype = '{0}' ", value);
            } else {
                sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
            }
        } else {
            sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
        }
        if (this.getUserBean() != null) {
            if (paraMap.containsKey("indexApp")) {
                if (paraMap.get("indexApp").toString().equals("1")) {

                } else {
                    sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
                            this.getUserBean().getUser().getId());
                }
            } else {
                sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
                        this.getUserBean().getUser().getId());
            }
        } else {
            return ResponseResult.ok("登录超时");
        }
        sql.appendSingle(" and CboApprovalNodeIns.state in ({0}) ", state);
        if (paraMap.containsKey("qry_dispdeptcode")) {
            String value = paraMap.get("qry_dispdeptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboDept.name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_dispusercode")) {
            String value = paraMap.get("qry_dispusercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboUser.name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_usercode")) {
            String value = paraMap.get("qry_usercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboUser.code = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_startdocdate")) {
            String value = paraMap.get("qry_startdocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboApprovalFlowIns.submitdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboApprovalFlowIns.submitdate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        sql.appendSingle(" ) tmpTable where ismobilapproval=1");
        int records = cboApprovalNodeInsService.selectCountExecute(sql.toString());
        dataMap = new HashMap();
        dataMap.put("records", records);
        dataMap.put("docTypes", listOffDocTypes);
        if (!paraMap.containsKey("count")) {
            listDataMap = cboApprovalNodeInsService.selectExecuteForPage(sql.toString(), page, rows, sidx, sord);
            for (Map mapRow : listDataMap) {
                setDispFields(mapRow, listOffDocTypes, doctType);
            }
        }
        result.put("dataMap", dataMap);
        result.put("dataList", listDataMap);
        return ResponseResult.ok(result);
    }


    @GetMapping(value = "/removeNoSourcList")
    public ResponseResult<Object> removeNoSourcList(@RequestParam(required = false) Map<String, Object> paraMap) {
        //paraMap = BaseUtil.decodeMap(paraMap);
        Map result = new HashMap<>();
        List<Map<String, Object>> listDataMap = new ArrayList<Map<String, Object>>();
        String doctType = ConvertUtil.convertToString(paraMap.get("doctype"));
        List<Map<String, Object>> listOffDocTypes = datacodeCache.getCodeListMap(doctType, "", "sortcode");
        StringBufferProxy docType = new StringBufferProxy();
        for (int num = 0; num < listOffDocTypes.size(); num++) {
            if (num != listOffDocTypes.size() - 1) {
                docType.appendSingle("'{0}',", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            } else {
                docType.appendSingle("'{0}'", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            }
        }
        Map dataMap = new HashMap<>();
        int page = ConvertUtil.convertToInt(paraMap.get("currentPage"));
        int rows = ConvertUtil.convertToInt(paraMap.get("pageSize"));
        String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
        String sord = ConvertUtil.convertToString(paraMap.get("sord"));
        String state = ConvertUtil.convertToString(paraMap.get("state"));
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle("select * from ( ");
        sql.appendSingle(" select  CboApprovalFlowIns.extendfield2 as deptcode,CboApprovalFlowIns.extendfield3 as usercode,CboApprovalFlowIns.submitdate as docdate,CboApprovalFlowIns.extendfield1 as docno,CboApprovalFlowIns.sourcetype as doctype, ");
        sql.appendSingle(
                " CboApprovalNode.name nodename,CboApprovalNode.approvalaction,CboApprovalNode.mobiledataaction,CboApprovalNode.mobileform,CboApprovalNode.extendfield9,CboApprovalNode.extendfield10,CboApprovalNode.ismobilapproval,  ");
        sql.appendSingle(" CboApprovalNodeIns.approvalopinion,");
        sql.appendSingle(
                " CboApprovalNodeIns.id,CboApprovalNodeIns.extendfield2,CboApprovalNodeIns.flowinsid,CboApprovalNodeIns.sourceid,CboApprovalNodeIns.sourcetype,");
        sql.appendSingle(" CboApprovalNodeIns.state,CboApprovalNodeIns.approvaldate ");
        sql.appendSingle(" from CboApprovalNodeIns  ");
        sql.appendSingle(" inner join CboApprovalFlowIns on CboApprovalNodeIns.flowinsid = CboApprovalFlowIns.id ");
        sql.appendSingle(" inner join CboApprovalFlow on CboApprovalFlowIns.flowid = CboApprovalFlow.id ");
        sql.appendSingle(" inner join CboApprovalNode on CboApprovalNodeIns.nodeid = CboApprovalNode.id ");
        sql.appendSingle(" left join CboDept on CboApprovalFlowIns.extendfield2 = CboDept.code ");
        sql.appendSingle(" left join CboUser on CboApprovalFlowIns.extendfield3 = CboUser.code ");
        if (paraMap.containsKey("qry_doctype")) {
            String value = paraMap.get("qry_doctype").toString();
            if (!StringUtil.isEmpty(value)) {
                sql.appendSingle(" where CboApprovalNodeIns.sourcetype = '{0}' ", value);
            } else {
                sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
            }
        } else {
            sql.appendSingle(" where CboApprovalNodeIns.sourcetype in ({0}) ", docType);
        }
        if (this.getUserBean() != null) {
            if (paraMap.containsKey("indexApp")) {
                if (paraMap.get("indexApp").toString().equals("1")) {

                } else {
                    sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
                            this.getUserBean().getUser().getId());
                }
            } else {
                sql.appendSingle(" and CboApprovalNodeIns.approvaluserid ='{0}'",
                        this.getUserBean().getUser().getId());
            }
        } else {
            return ResponseResult.ok("登录超时");
        }
//			sql.appendSingle(" and CboApprovalNodeIns.state in ({0}) ", state);
        if (paraMap.containsKey("qry_dispdeptcode")) {
            String value = paraMap.get("qry_dispdeptcode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboDept.name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_dispusercode")) {
            String value = paraMap.get("qry_dispusercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboUser.name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_usercode")) {
            String value = paraMap.get("qry_usercode").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboUser.code = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_startdocdate")) {
            String value = paraMap.get("qry_startdocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboApprovalFlowIns.submitdate >= {0} ", SQLAdapter.toDateLong(value + " 00:00:00"));
        }
        if (paraMap.containsKey("qry_enddocdate")) {
            String value = paraMap.get("qry_enddocdate").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and CboApprovalFlowIns.submitdate <= {0} ", SQLAdapter.toDateLong(value + " 23:59:59"));
        }
        sql.appendSingle(" ) tmpTable where ismobilapproval=1");
        int records = cboApprovalNodeInsService.selectCountExecute(sql.toString());
        dataMap = new HashMap();
        dataMap.put("records", records);
        dataMap.put("docTypes", listOffDocTypes);
        if (!paraMap.containsKey("count")) {
            listDataMap = cboApprovalNodeInsService.selectExecuteForPage(sql.toString(), page, rows, sidx, sord);
            for (Map mapRow : listDataMap) {
                setDispFields(mapRow, listOffDocTypes, doctType);
            }
        }
        List deletS = new ArrayList<>();
        for (Map map2 : listDataMap) {
            Object aObject = ((BasicService) SpringUtil.getBean(toLowerCaseFirstOne(map2.get("sourcetype").toString()) + "Service")).queryById(map2.get("sourceid").toString());
            if (aObject == null) {
                deletS.add(map2);
                System.out.println(map2.get("id"));
                cboApprovalNodeInsService.deleteByWhere("id = " + map2.get("id").toString() + "");
            }
        }
        result.put("dataMap", dataMap);
        result.put("dataList", listDataMap);
        return ResponseResult.ok(result);
    }

    /**
     * 首字母转小写
     *
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * @param mapRow
     * @param listOffDocTypes
     * @throws
     * @Title: setDispFields
     * @return: void
     * @Description: 设置显示字段
     */
    private void setDispFields(Map mapRow, List<Map<String, Object>> listOffDocTypes, String doctype) {
        DatacodeCache datacodeCache = (DatacodeCache) SpringUtil.getBean("datacodeCache");
        String temp = "";
        if (mapRow.get("state") != null) {
            temp = mapRow.get("state").toString();
            mapRow.put("dispstate", datacodeCache.getValueDynamic("TapApprovalNodeState", temp, "code", "name"));
        }
        if (mapRow.get("usercode") != null) {
            temp = mapRow.get("usercode").toString();
            mapRow.put("username", datacodeCache.getValueDynamic("CboUser", temp, "code", "name"));
        }
        if (mapRow.get("orgcode") != null) {
            temp = mapRow.get("orgcode").toString();
            mapRow.put("disporgcode", datacodeCache.getValueDynamic("CboOrg", temp, "code", "name"));
        }
        if (mapRow.get("deptcode") != null) {
            // 研发本部展示具体部门，其他的展示一级部门
            temp = mapRow.get("deptcode").toString();
            if (temp.startsWith("2201") || temp.startsWith("2212") || temp.startsWith("D1F01_0101") || temp.startsWith("2404") || temp.startsWith("D101")) {
                mapRow.put("dispdeptcode", datacodeCache.getValueDynamic("CboDept", temp, "code", "name"));
            } else {
				// 获取一级部门
                String fullname = datacodeCache.getValueDynamic("CboDeptFull", temp, "code", "name");
                mapRow.put("dispdeptcode", fullname.split("\\\\")[1]);
            }
        }
        if (mapRow.get("nodetype") != null) {
            temp = mapRow.get("nodetype").toString();
            mapRow.put("dispnodetype", datacodeCache.getValueDynamic("TapApprovalNodeType", temp, "code", "name"));
        }
        if (mapRow.get("extendfield2") == null || mapRow.get("extendfield2").toString().equals("")) {
            if (listOffDocTypes != null) {
                temp = mapRow.get("nodename").toString();
                mapRow.put("extendfield2", temp);
            } else {
                temp = mapRow.get("dispnodeid").toString();
                mapRow.put("extendfield2", temp);
            }

        }
        if (mapRow.get("doctype") != null && listOffDocTypes != null) {
            temp = mapRow.get("doctype").toString();
            for (Map listOffDocType : listOffDocTypes) {

                if (temp.equals(listOffDocType.get("code"))) {
                    mapRow.put("dispdoctype", datacodeCache.getValueDynamic(doctype, temp, "code", "name"));
                    if (StringUtil.isEmpty(ConvertUtil.convertToString(listOffDocType.get("extendfield1")))) {
                        if ("1".equals(ConvertUtil.convertToString(listOffDocType.get("extendfield1")))) {
                            mapRow.put("webDesign", "1");//电脑端配置详情页
                        }
                    } else {
                        mapRow.put("webDesign", "0");//老的详情页
                    }

                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
    }

    /**
     * 手机端查询审批节点历史
     *
     * @author: jiangtao
     * @date: 2020年4月15日下午1:39:58
     * @params:
     * @return_type: ResponseResult<Object>
     * @description:
     * @modify:
     */
    @GetMapping(value = "/listHistoryRecord")
    public ResponseResult<Object> listHistoryRecord(@RequestParam(required = false) Map<String, Object> paraMap) {
        //paraMap = BaseUtil.decodeMap(paraMap);
        Map result = new HashMap<>();
//		String sidx = ConvertUtil.convertToString(paraMap.get("sidx"));
        String sord = ConvertUtil.convertToString(paraMap.get("sord"));
        StringBufferProxy sql = new StringBufferProxy();
        List<Map<String, Object>> listDataMap = new ArrayList<Map<String, Object>>();
        sql.appendSingle(" sourceid = {0} ", paraMap.get("sourceId"));
        sql.appendSingle(" and sourcetype = '{0}' ", paraMap.get("sourceType"));
        List<Map<String, Object>> listFlow = cboApprovalNodeInsService.queryMapForPage(sql.toString(), 1, 100, "createon desc,id", sord);
        if (listFlow != null && listFlow.size() > 0) {

            listDataMap = listFlow;
            for (Map mapRow : listDataMap) {
				System.out.println(mapRow.get("nodeid"));
				CboApprovalNodeEntity node = cboApprovalNodeService.queryById(ConvertUtil.convertToString(mapRow.get("nodeid")));
				if (node != null) {
					int nodetype = node.getNodetype();
					mapRow.put("nodetype", nodetype);
					String nodetypename = "";
					if((nodetype == 2 || nodetype == 3 || nodetype == 4)) {
						nodetypename = datacodeCache.getValueDynamic("TapApprovalNodeType", nodetype+"", "code", "name");
						if(nodetypename.lastIndexOf("节点")>1) {
							nodetypename = nodetypename.substring(0,nodetypename.lastIndexOf("节点"));
						}
					}
					mapRow.put("dispnodetype", nodetypename);
				}
			}
        } else {
            return ResponseResult.ok("没有查询到相关审批历史！");
        }
        result.put("dataList", listDataMap);
        return ResponseResult.ok(result);
    }
    @GetMapping({"/myMobileApprovalCount"})
    public ResponseResult<Object> myMobileApprovalCount(@RequestParam(required = false) Map<String, Object> paraMap) {
        Map dataMap = new HashMap();
        Map result = new HashMap();
        StringBufferProxy docType = new StringBufferProxy();
        List<Map<String, Object>> listOffDocTypes = this.datacodeCache.getCodeListMap(paraMap.get("doctype").toString(), "", "sortcode");
        String userid = this.datacodeCache.getValueDynamic("CboUser", paraMap.get("usercode").toString(), "code", "id");

        for(int num = 0; num < listOffDocTypes.size(); ++num) {
            if (num != listOffDocTypes.size() - 1) {
                docType.appendSingle("'{0}',", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            } else {
                docType.appendSingle("'{0}'", ConvertUtil.convertToString(listOffDocTypes.get(num).get("code")));
            }
        }

        if (docType.toString().equals("")) {
            return ResponseResult.error("未查询到可审批的单据类型");
        } else {
            StringBufferProxy sql = new StringBufferProxy();
            sql.appendLineSingle("select approvaluserid from CboApprovalNodeIns "
                    + "INNER JOIN CboApprovalFlowIns ON "
                    + "CboApprovalNodeIns.flowinsid = CboApprovalFlowIns.id "
                    + "INNER JOIN CboApprovalNode ON "
                    + "CboApprovalNodeIns.nodeid = CboApprovalNode.id "
                    + "AND CboApprovalNode.ismobilapproval = 1 "
                    + "WHERE CboApprovalNodeIns.state = '1' "
                    + "AND CboApprovalNodeIns.enabled = 1");
            if (paraMap.containsKey("indexApp") && paraMap.get("indexApp").toString().equals("1")) {
                sql.appendLineSingle(" and CboApprovalNodeIns.sourcetype in ({0})", docType.toString());
            } else {
                sql.appendLineSingle(" and CboApprovalNodeIns.approvaluserid = '{0}' and CboApprovalNodeIns.sourcetype in ({1})", userid, docType.toString());
            }

            int records = this.cboApprovalNodeService.selectCountExecute(sql.toString());
            dataMap.put("records", records);
            result.put("dataMap", dataMap);
            return ResponseResult.ok(result);
        }
    }
}
